package com.phpxiu.app.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.util.Log;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @file
 * @brief 多媒体语音管理器
 * @author 吴金洲
 * @note 录制和播放语音消息
 *
 */
public class VoiceManager {

    public final static String TAG="VoiceManager";

    private static VoiceManager instance = new VoiceManager();

    public Context context;

    private String mFileName = null;

    private MediaRecorder mRecorder = null;

    private long startTime;

    private long timeInterval;

    private boolean isRecording;


    private MediaPlayer player;

    private OnVoiceEventListener eventListener;

    public static VoiceManager getInstance(){
        return instance;
    }


    private VoiceManager() {
        mFileName=FileManager.getCacheFilePath("tempAudio");
        player=new MediaPlayer();
    }

    /**
     * 初始化管理器
     * @param c
     */
    public void init(Context c){
        context=c;
    }

    /**
     * 开始录音
     */
    public void startRecording() {
        if (mFileName == null) return;
        if (isRecording){
            mRecorder.release();
            mRecorder = null;
        }
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        startTime = System.currentTimeMillis();
        try {
            mRecorder.prepare();
            mRecorder.start();
            isRecording = true;
        } catch (Exception e){
            Log.e(TAG, "prepare() failed");
        }

    }

    /**
     * 停止录音
     */
    public void stopRecording() {
        if (mFileName == null) return;
        timeInterval = System.currentTimeMillis() - startTime;
        try{
            if (timeInterval>1000){
                mRecorder.stop();
            }
            mRecorder.release();
            mRecorder = null;
            isRecording =false;
        }catch (Exception e){
            Log.e(TAG, "release() failed");
        }

    }


    /**
     * 获取录音文件
     */
    public byte[] getDate() {
        if (mFileName == null) return null;
        try{
            return readFile(new File(mFileName));
        }catch (IOException e){
            Log.e(TAG, "read file error" + e);
            return null;
        }
    }

    /**
     * 获取录音文件地址
     */
    public String getFilePath(){
        return mFileName;
    }


    /**
     * 获取录音时长,单位秒
     */
    public long getTimeInterval() {
        return timeInterval/1000;
    }


    /**
     * 将文件转化为byte[]
     *
     * @param file 输入文件
     */
    private static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }

    /**
     * 播放语音
     * @param inputStream
     */
    public void play(FileInputStream inputStream){
        try{
            if (eventListener != null){
                eventListener.onVoiceStop();
            }
            player.reset();
            player.setDataSource(inputStream.getFD());
            player.prepare();
            player.start();
        }catch (IOException e){
            Log.e(TAG, "play error:" + e);
            if (eventListener != null){
                eventListener.onVoiceStop();
            }
        }


    }

    /**
     * 停止播放
     */
    public void stop(){
        if (player != null && player.isPlaying()){
            player.stop();
        }
    }

    /**
     * 获取语音文件时长
     * @param path
     * @return
     */
    public long getDuration(String path){
        player = MediaPlayer.create(context, Uri.parse(path));
        return player.getDuration();
    }


    /**
     * 播放监听设置
     * @param eventListener
     */
    public void setEventListener(final OnVoiceEventListener eventListener) {
        if (player != null){
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    eventListener.onVoiceStop();
                }
            });
        }
        this.eventListener = eventListener;
    }

    /**
     * 播放器事件监听
     */
    public interface OnVoiceEventListener{
        void onVoiceStop();
    }
}
